package com.mybed.crm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mybed.crm.anno.Log;
import com.mybed.crm.exception.BaseException;
import com.mybed.crm.mapper.RoleMapper;
import com.mybed.crm.pojo.dto.PageRoleDto;
import com.mybed.crm.pojo.dto.RoleDto;
import com.mybed.crm.pojo.dto.RoleStatusDto;
import com.mybed.crm.pojo.pojo.Role;
import com.mybed.crm.pojo.pojo.User;
import com.mybed.crm.result.MenuResult;
import com.mybed.crm.result.PageResult;
import com.mybed.crm.result.Result;
import com.mybed.crm.result.ResultP;
import com.mybed.crm.service.MenuService;
import com.mybed.crm.service.RoleService;
import com.mybed.crm.service.UserService;
import com.mybed.crm.utils.thread.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/system/role")
@Slf4j
public class RoleController {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @GetMapping("/list")
    public PageResult listRoleQuery(PageRoleDto dto){
        LambdaQueryWrapper<Role> wrapper=new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(dto.getRoleName()), Role::getRoleName,dto.getRoleName());
        wrapper.like(StringUtils.hasLength(dto.getRoleKey()), Role::getRoleKey,dto.getRoleKey());
        wrapper.eq(dto.getStatus()!=null, Role::getStatus,dto.getStatus());
        if(dto.getParams()!=null){
            wrapper.between(StringUtils.hasLength(dto.getParams().get("beginTime"))&&StringUtils.hasLength(dto.getParams().get("endTime")), Role::getCreateTime,dto.getParams().get("beginTime"),dto.getParams().get("endTime"));
        }
        IPage<Role> page=new Page<>(dto.getPageNum(),dto.getPageSize());
        IPage<Role> iPage=roleMapper.selectPage(page,wrapper);
        PageResult result=new PageResult();
        result.insertData(iPage);
        return result;
    }
    @Log("添加角色")
    @PostMapping
    public ResultP addRole(@RequestBody RoleDto dto){
        log.info("新增角色,role={}",dto);
        Role one = roleMapper.selectOne(Wrappers.<Role>lambdaQuery().eq(Role::getRoleName, dto.getRoleName()));
        if(one!=null){
            throw new BaseException("用户已存在");
        }
        Role role=new Role();
        BeanUtils.copyProperties(dto,role);
        User user = userService.getById(UserThreadLocalUtil.getUser());
        role.setCreateBy(user.getUserName());
        role.setCreateTime(LocalDateTime.now());
        role.setDeptIds(StringUtils.collectionToCommaDelimitedString(dto.getDeptIds()));
        role.setMenuIds(StringUtils.collectionToCommaDelimitedString(dto.getMenuIds()));
        roleMapper.insert(role);
        return ResultP.success();
    }
    /**
     * 根据Id查询角色
     */
    @GetMapping("/{id}")
    public Result selectByOne(@PathVariable String id){
        Role byId = roleService.getById(id);
        if(!StringUtils.hasLength(byId.getMenuIds())){
            byId.setMenuIds(null);
        }
        if(!StringUtils.hasLength(byId.getDeptIds())){
            byId.setDeptIds(null);
        }
        return Result.success(byId);
    }
    @Log("修改角色")
    @PutMapping
    public ResultP updateRole(@RequestBody RoleDto dto){
        User user = userService.getById(UserThreadLocalUtil.getUser());
        Role role=new Role();
        BeanUtils.copyProperties(dto,role);
        role.setUpdateBy(user.getUserName());
        role.setUpdateTime(LocalDateTime.now());
        role.setDeptIds(StringUtils.collectionToCommaDelimitedString(dto.getDeptIds()));
        role.setMenuIds(StringUtils.collectionToCommaDelimitedString(dto.getMenuIds()));
        roleService.updateById(role);
        return ResultP.success();
    }
    @Log("删除角色")
    @DeleteMapping("/{id}")
    public ResultP deleteById(@PathVariable String id){
        roleService.removeById(id);
        return ResultP.success();
    }
    @Log("修改角色状态")
    @PutMapping("/changeStatus")
    public ResultP changeStatus(@RequestBody RoleStatusDto dto){
        Role role = roleMapper.selectById(dto.getRoleId());
        role.setStatus(dto.getStatus());
        roleMapper.updateById(role);
        return ResultP.success();
    }

}
